﻿#include <QSqlQuery>
#include <QSqlField>
#include <QSqlError>
#include <QDebug>
#include "JZDbConfigTable.h"

JZDbConfigTable::JZDbConfigTable() 
{ 
    m_table.tableName = "ConfigTable";
    m_table.keyIndex = 0;
    m_table.record.append(QSqlField("key", QVariant::String));
    m_table.record.append(QSqlField("value", QVariant::ByteArray));
}

JZDbConfigTable::~JZDbConfigTable() 
{ 

}

QString JZDbConfigTable::tableName()
{
    return m_table.tableName;
}

void JZDbConfigTable::setTableName(const QString& tableName)
{
    m_table.tableName = tableName;
}

const JZDbTable& JZDbConfigTable::table()
{
    return m_table;
}

bool JZDbConfigTable::hasConfig(const QString& key)
{    
    QSqlQuery query;
    query.prepare("SELECT 1 FROM ConfigTable WHERE key = :key");
    query.bindValue(":key", key);
    if (query.exec() && query.next()) {
        return true;
    }
    return false;
}

void JZDbConfigTable::addConfig(QString name)
{
    QSqlQuery query;
    // 插入一条初始记录，key 和 buffer 为 NULL
    query.prepare("INSERT OR IGNORE INTO ConfigTable (key, value) VALUES (:name, NULL)");
    query.bindValue(":name", name);
    if (!query.exec()) {
        qDebug() << "Failed to add config:" << query.lastError().text();
    }
}

void JZDbConfigTable::setConfigBuffer(QString key, const QByteArray &buffer)
{
    QSqlQuery query;
    // 插入或替换记录
    query.prepare("INSERT OR REPLACE INTO ConfigTable (key, value) VALUES (:key, :value)");
    query.bindValue(":key", key);
    query.bindValue(":value", buffer);
    if (!query.exec()) {
        qDebug() << "Failed to set config buffer:" << query.lastError().text();
    }
}

QByteArray JZDbConfigTable::getConfigBuffer(QString key)
{
    QByteArray buffer;

    QSqlQuery query;
    // 根据 name 和 key 查询 buffer
    query.prepare("SELECT value FROM ConfigTable WHERE key = :key");
    query.bindValue(":key", key);
    if (query.exec() && query.next()) {
        buffer = query.value(0).toByteArray();
    }
    else {
        qDebug() << "Failed to get config buffer:" << query.lastError().text();
    }
    return buffer;
}